#!/usr/bin/env node

const inquirer = require('inquirer')
const fs = require('fs')
const path = require("path");
const templateList = require(`${__dirname}/../template`)
const { showTable } = require(`${__dirname}/../util/showTable`)
const symbols = require('log-symbols')
const { exec } = require('child_process')
const chalk = require('chalk')
chalk.level = 3

let question = [
    {
        name: 'name',// 问题对应的属性
        type: 'input',// 问题类型为填空题
        message: '请输入模板名称', // 问题描述
        validate(val) {
            if (!val) {
                return chalk.red('name is required!')
            } else if (templateList[val]) {
                return 'Template has already existed!'
            } else {
                return true
            }
        }
    },
    {
        name: 'url',
        type: 'input',
        message: '请输入模板地址',
        validate(val) {
            if (!val) {
                return chalk.red('The url is required!')
            }
            return true
        }
    }
]
inquirer.prompt(question).then((answers) => {
    let { name, url } = answers;

    // 打印再控制台上
    templateList[name] = url.replace(/[\u0000-\u0019]/g, '') // 过滤 unicode 字符
    fs.writeFile(`${__dirname}/../template.json`, JSON.stringify(templateList), 'utf-8', err => {
        if (err) console.log(chalk.red(symbols.error), chalk.red(err))
        console.log('\n')
        console.log(chalk.green(symbols.success), chalk.green('Add a template successfully!\n'))
        console.log(chalk.green('The latest templateList is: \n'))
        showTable(templateList)
    })
    //从git下载到本地指定路径
    exec(`git clone ${url} ` + path.resolve(__dirname, `../templates/${name}`), (error, stdout, stderr) => {
        if (error) { // 当有错误时打印出错误并退出操作
            console.log(chalk.red(error))
            process.exit()
        }
        console.log(chalk.green('初始化完成'))
        process.exit() // 退出这次命令行操作
    })
})